<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/2/21 0021
 * Time: 上午 8:58
 */

namespace app\single\api;


use think\Db;
use think\exception\DbException;

class Notice
{
    public function run($params): array
    {
        $ret["ret"] = 1;
        $ret["data"]["syn_status"] = 4;
        $ret["data"]["syn_desc"] = "同步成功";
        $data = json_decode(base64_decode($params["data"]), true);
        $addArr["type"] = $data["place"];
        $addArr["content"] = str_replace(["&lt;", "&#039;", "&quot;", "&gt;"], ["<", '"', '"', ">"], $data["content"]);
        $addArr["begin_time"] = $data["begin_time"];
        $addArr["end_time"] = $data["end_time"];
        $addArr["interval"] = $data["interval"];
        $addArr["status"] = $data["status"] ?? 1;

        $noticeErl = false;
        $check = Db::table(config("database.game") . ".sys_notice")
            ->where("id", $data["notice_id"])
            ->value("id");
        switch ($data["syn_status"]) {
            case 1:
            case 2:
                //添加同步 / 修改同步
                try {
                    if ($check) {
                        Db::table(config("database.game") . ".sys_notice")
                            ->where("id", $data["notice_id"])
                            ->update($addArr);
                    } else {
                        $addArr["id"] = $data["notice_id"];
                        Db::table(config("database.game") . ".sys_notice")
                            ->insert($addArr);
                    }
                    $noticeErl = true;
                } catch (DbException $e) {
                    $ret["data"]["syn_status"] = 5;
                    $ret["data"]["syn_desc"] = "同步失败：" . $e->getMessage();
                }
                break;
            case 3:
                if ($check) {
                    if (Db::table(config("database.game") . ".sys_notice")->delete($data["notice_id"])) {
                        $noticeErl = true;
                        $ret["data"]["syn_status"] = 7;
                    } else {
                        $ret["data"]["syn_status"] = 6;
                        $ret["data"]["syn_desc"] = "删除失败";
                    }
                } else {
                    $ret["data"]["syn_status"] = 7;
                }
                break;
            default:
                $ret["data"]["syn_status"] = 5;
                $ret["data"]["syn_desc"] = "非法同步状态";
                break;
        }
        if ($noticeErl) {
            try {
                $res = PHP2Erlang(BACKGROUND_NOTICE, [$data["notice_id"]]);
            } catch (\Exception $e) {
                $ret["data"]["syn_status"] = 5;
                $ret["data"]["syn_desc"] = "同步失败：" . $e->getMessage();
                return $ret;
            }
        }
        return $ret;
    }
}